package com.col.flutterplugin.float_button_overlay.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
//import android.graphics.drawable.Icon;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.Timer;
import java.util.TimerTask;
import com.col.flutterplugin.float_button_overlay.FloatBallManager;
import com.col.flutterplugin.float_button_overlay.FloatButtonOverlayPlugin;
import com.col.flutterplugin.float_button_overlay.floatball.FloatBallCfg;
import com.col.flutterplugin.float_button_overlay.utils.BackGroudSeletor;
import com.col.flutterplugin.float_button_overlay.utils.DensityUtil;
//import io.flutter.embedding.engine.FlutterEngine;
//import io.flutter.embedding.engine.dart.DartExecutor;
//import io.flutter.plugin.common.MethodChannel;
import static com.col.flutterplugin.float_button_overlay.utils.Constants.BROADCAST_FINISH_APP;
import static com.col.flutterplugin.float_button_overlay.utils.Constants.CHANNEL;
import static com.col.flutterplugin.float_button_overlay.utils.Constants.TAG;

public class FloatButtonService extends Service {

    Context context;
//    FlutterEngine flutterEngine;
//    MethodChannel channel;
    LocalBroadcastManager mLocalBroadcastManager;
    FloatButtonService mService;

    private long startClickTime;
    private Timer timer;
    private TimerTask timerTask;
    private String packageName;
    private String activityName;
    private FloatBallManager mFloatballManager;

    private final IBinder mBinder = new LocalBinder();
    private static final int NOTIFICATION_ID = -1326875;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void onCreate() {

//        flutterEngine = new FlutterEngine(this);
//        flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
//        channel = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        startFloatButtonLayout();

    }

    private void startAppIntent(String packageName, String activityName) {

        Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
        try {
            pendingIntent.send();
        } catch (PendingIntent.CanceledException e){
            e.printStackTrace();
        }

    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(TAG, "Service started");
        context = getApplicationContext();
        boolean showOverLay = false;

        try {

            Bundle extras = intent.getExtras();
            if (extras != null) {
                Log.i(TAG, extras.toString());
                packageName = extras.getString("packageName");
                activityName = extras.getString("activityName");
                showOverLay = extras.getBoolean("showOverlay");
                Log.i(TAG, extras.toString());

            } else {
                Log.i(TAG, "No intent Extras");
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        if(showOverLay){
            if(mFloatballManager != null){
                mFloatballManager.show();
            }else {
                startFloatButtonLayout();
                mFloatballManager.show();
            }

        }else {
            if(mFloatballManager != null){
                mFloatballManager.hide();
            }
        }

        if (Build.VERSION.SDK_INT >= 26) {
            Log.i(TAG, "for system version >= Android O, we just ignore increasingPriority "
                    + "job to avoid crash or toasts.");
            return START_STICKY;
        }

        if ("ZUK".equals(Build.MANUFACTURER)) {
            Log.i(TAG, "for ZUK device, we just ignore increasingPriority "
                    + "job to avoid crash.");
            return START_STICKY;
        }

        try {
            Notification notification = new Notification();
            if (Build.VERSION.SDK_INT < 18) {
                startForeground(NOTIFICATION_ID, notification);
            } else {
//                startForeground(NOTIFICATION_ID, notification);
                // start InnerService
                startService(new Intent(this, InnerService.class));
            }
        } catch (Throwable e) {
            Log.i(TAG, "try to increase patch process priority error:" + e);
        }

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "in onBind()");
        return mBinder;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "in onRebind()");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "Unbinding Service");
        return false;
    }

    @Override
    public void onDestroy() {        

        try {
            mFloatballManager.hide();
//            channel = null;
//            flutterEngine.destroy();
            mFloatballManager = null;
//            sendBroadcastToFinishApp();
        } catch (Exception e) {
            
        }
    }

    private void sendBroadcastToFinishApp() {

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
        localBroadcastManager.sendBroadcast(new Intent(BROADCAST_FINISH_APP));

    }

    private void startFloatButtonLayout() {

        try {

            //1 初始化悬浮球配置，定义好悬浮球大小和icon的drawable
            int ballSize = DensityUtil.dip2px(this, 60);
            Drawable ballIcon = BackGroudSeletor.getdrawble("ic_floatball", this);
            //可以尝试使用以下几种不同的config。
//        FloatBallCfg ballCfg = new FloatBallCfg(ballSize, ballIcon);
//        FloatBallCfg ballCfg = new FloatBallCfg(ballSize, ballIcon, FloatBallCfg.Gravity.LEFT_CENTER,false);
//        FloatBallCfg ballCfg = new FloatBallCfg(ballSize, ballIcon, FloatBallCfg.Gravity.LEFT_BOTTOM, -100);
//        FloatBallCfg ballCfg = new FloatBallCfg(ballSize, ballIcon, FloatBallCfg.Gravity.RIGHT_TOP, 100);
            FloatBallCfg ballCfg = new FloatBallCfg(ballSize, ballIcon, FloatBallCfg.Gravity.RIGHT_CENTER);
            //设置悬浮球不半隐藏
            ballCfg.setHideHalfLater(false);
            mFloatballManager = new FloatBallManager(getApplicationContext(), ballCfg);
            if (mFloatballManager.getMenuItemSize() == 0) {
                mFloatballManager.setOnFloatBallClickListener(new FloatBallManager.OnFloatBallClickListener() {
                    @Override
                    public void onFloatBallClick() {
                        if(packageName != null && !packageName.isEmpty()){
                            startAppIntent(packageName, activityName);
                        }
                        Log.i(TAG, "Will click on channel " + CHANNEL);
                        FloatButtonOverlayPlugin.invokeCallBack("onClickCallback", null);
                        Log.i(TAG, "Clicked");
                    }
                });
            }
            FloatButtonOverlayPlugin.invokeCallBack("callback", null);
        }catch (Exception e){
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }

    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
//                        channel.invokeMethod("callback", null);
                        Log.i(TAG, "Send to Flutter");
                    }
                });
            }
        };
    }

    public void stopTimerTask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void startTimer() {

        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, send event to dart code
        timer.schedule(timerTask, 5000, 5000); //
    }

    public class LocalBinder extends Binder {
        public FloatButtonService getService() {
            return FloatButtonService.this;
        }
    }

    public static class InnerService extends Service {
        @Override
        public void onCreate() {
            super.onCreate();
            try {
                startForeground(NOTIFICATION_ID, new Notification());
            } catch (Throwable e) {
                Log.e(TAG, "InnerService set service for push exception:%s.", e);
            }
            stopSelf();
        }

        @Override
        public void onDestroy() {
            stopForeground(true);
            super.onDestroy();
        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }


}